/**
 * ES9 es2018
 * 异步迭代 for-await-of
 * 
 * Symbol.asyncIterator
 */
const arr = [1,2,3,4]

// 同步迭代
arr[Symbol.iterator] = function () {
  let nextIndex = 0
  return {
    next() {
      return nextIndex < arr.length ?{
        value: arr[nextIndex++],
        done: false
      } : {
        value: undefined,
        done: true
      }
    }
  }
}
for(let i of arr) {
   console.log(i)
}

/**
 * 数组 存异步操作，等待一个异步任务完成再执行另一个异步任务
 * 
 */
function getPromise(time) {
  return new Promise((resolve, reject) => {
    setTimeout(()=>{
      resolve({
        value: time,
        done: false
      })
    }, time)
  })
}
const arr2 = [getPromise(1000),getPromise(2000),getPromise(3000)]
arr2[Symbol.asyncIterator] = function () {
  let nextIndex = 0
  return {
    next() {
      return nextIndex < arr2.length ? arr2[nextIndex++] : Promise.resolve({
        value: undefined,
        done: true
      })
    }
  }
}

async function test(){
  for await (let i of arr2) {
    console.log(i)
  }
}
test()

